package org.stone.project.tx.service.impl;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.stone.project.tx.pojo.dto.UserInfoDto;
import org.stone.project.tx.service.TokenService;

import javax.annotation.PostConstruct;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 内存认证实现认证
 */
@Service
public class InMemoryTokenServiceImpl implements TokenService {
    private ConcurrentHashMap<String, UserInfoDto> tokenMap = new ConcurrentHashMap();

    @PostConstruct
    public void getToken(){
        for (int i = 0; i < 20; i++) {
            UserInfoDto userInfoDto = new UserInfoDto();
            userInfoDto.setId(i+"");
            userInfoDto.setNickname(i+"");
            userInfoDto.setHeadImgUrl(i+"");
            tokenMap.put(i+"",userInfoDto);
        }
    }

    @Override
    public UserInfoDto getUserInfoByToken(String token) {
        if (ObjectUtil.isNotEmpty(token)){
            UserInfoDto userInfoDto = tokenMap.get(token);
            return userInfoDto;
        }
        return null;
    }

    @Override
    public UserInfoDto getWebUserInfoByToken() {
        String auth = ((ServletRequestAttributes) (RequestContextHolder.getRequestAttributes())).getRequest().getHeader("Auth");
        return getUserInfoByToken(auth);
    }
}
